package com.gxd.dao.impl;

import com.gxd.dao.AdminDao;
import com.gxd.domain.User;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl implements AdminDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
    @Override
    public User findByUAndP(String username, String password) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where username=? and password= md5(?) and role=0 ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> findByUid() {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where flag=1 and role=1 ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> findByinvalid() {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where flag=2 and role=1 ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> findByMore(String where, List<Object> params) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user"+where;
        try {
            return queryRunner.query(sql,new BeanListHandler<>(User.class),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteUser(int id) {
        String sql=" delete from tb_user where id = ?";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
